"""
云端健康检查路由
"""
import psutil
import time
from datetime import datetime
from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import text

from database import get_db, Node
from config import config
from utils import LogManager
from response_utils import success_response

router = APIRouter(prefix="/api/v1", tags=["健康检查"])

# 服务启动时间
SERVICE_START_TIME = time.time()

@router.get("/health")
async def basic_health_check():
    """基础健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "uptime": time.time() - SERVICE_START_TIME,
        "service": "云端AI训练系统"
    }

@router.get("/health/detailed")
async def detailed_health_check(db: Session = Depends(get_db)):
    """详细健康检查"""
    logger = LogManager.get_logger("HealthCheck")
    
    health_info = {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "uptime": time.time() - SERVICE_START_TIME,
        "service": "云端AI训练系统",
        "version": config.api.version,
        "components": {}
    }
    
    try:
        # 检查数据库连接
        try:
            db.execute(text("SELECT 1"))
            health_info["components"]["database"] = {
                "status": "healthy",
                "message": "数据库连接正常"
            }
        except Exception as e:
            logger.error(f"数据库连接检查失败: {str(e)}")
            health_info["components"]["database"] = {
                "status": "unhealthy",
                "error": str(e)
            }
            health_info["status"] = "degraded"
        
        # 检查边缘节点状态
        try:
            total_nodes = db.query(Node).count()
            online_nodes = db.query(Node).filter(Node.status == 'online').count()
            edge_nodes = db.query(Node).filter(Node.node_type == 'edge').count()
            online_edge_nodes = db.query(Node).filter(
                Node.node_type == 'edge', 
                Node.status == 'online'
            ).count()
            
            health_info["components"]["nodes"] = {
                "status": "healthy" if total_nodes > 0 else "warning",
                "total_nodes": total_nodes,
                "online_nodes": online_nodes,
                "edge_nodes": edge_nodes,
                "online_edge_nodes": online_edge_nodes,
                "message": f"共 {total_nodes} 个节点，{online_nodes} 个在线"
            }
            
            if total_nodes == 0:
                health_info["status"] = "warning"
                
        except Exception as e:
            logger.error(f"节点状态检查失败: {str(e)}")
            health_info["components"]["nodes"] = {
                "status": "error",
                "error": str(e)
            }
            health_info["status"] = "degraded"
        
        # 检查系统资源
        try:
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            
            health_info["components"]["system"] = {
                "status": "healthy",
                "cpu_usage": f"{cpu_percent:.1f}%",
                "memory_usage": f"{memory.percent:.1f}%",
                "disk_usage": f"{disk.percent:.1f}%",
                "memory_available": f"{memory.available / 1024**3:.1f}GB",
                "disk_free": f"{disk.free / 1024**3:.1f}GB"
            }
            
            # 资源使用率过高时发出警告
            if cpu_percent > 90 or memory.percent > 90 or disk.percent > 90:
                health_info["components"]["system"]["status"] = "warning"
                health_info["status"] = "warning"
                
        except Exception as e:
            logger.warning(f"系统资源检查失败: {str(e)}")
            health_info["components"]["system"] = {
                "status": "unknown",
                "error": str(e)
            }
        
        # 检查关键目录
        try:
            from pathlib import Path
            
            dirs_to_check = {
                "models": Path("models"),
                "datasets": Path("datasets"),
                "logs": Path("logs"),
                "temp": Path("temp")
            }
            
            dir_status = {}
            for name, path in dirs_to_check.items():
                dir_status[name] = {
                    "exists": path.exists(),
                    "is_dir": path.is_dir() if path.exists() else False,
                    "writable": path.exists() and path.is_dir() and path.stat().st_mode & 0o200,
                    "file_count": len(list(path.iterdir())) if path.exists() and path.is_dir() else 0
                }
            
            health_info["components"]["directories"] = {
                "status": "healthy",
                "details": dir_status
            }
            
            # 检查是否有目录不存在或不可写
            missing_dirs = [name for name, info in dir_status.items() if not info["exists"]]
            unwritable_dirs = [name for name, info in dir_status.items() if info["exists"] and not info["writable"]]
            
            if missing_dirs or unwritable_dirs:
                health_info["components"]["directories"]["status"] = "warning"
                health_info["components"]["directories"]["issues"] = {
                    "missing": missing_dirs,
                    "unwritable": unwritable_dirs
                }
                if health_info["status"] == "healthy":
                    health_info["status"] = "warning"
                    
        except Exception as e:
            logger.warning(f"目录检查失败: {str(e)}")
            health_info["components"]["directories"] = {
                "status": "unknown",
                "error": str(e)
            }
        
        return success_response(data=health_info, message="健康检查完成")
        
    except Exception as e:
        logger.error(f"详细健康检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")

@router.get("/health/ping")
async def ping():
    """简单的ping接口"""
    return {"ping": "pong", "timestamp": datetime.now().isoformat()} 